import React from 'react';
import { Link } from 'react-router-dom';
import styles from './studentDetail.less';
import { Modal, Button, Input, Table, Form, Select, message, Spin } from 'antd';

const { Option } = Select;
import { SdEdit, UsereditObjectUp, UsereditObjectDown } from './sdEdit';
import request from '@/http';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { GNEditObject } from '@/pages/admin/projectTeam/groupNameEdit';
import qs from 'qs';

const { confirm } = Modal;

export default (props: any) => {
  const [loadingState, setLoadingState] = React.useState({ loading: true });
  const id = window.localStorage.getItem('id');

  const columns = [
    {
      title: '院系',
      dataIndex: 'collegesName',
      key: 'collegesName',
      width: 75,
    },

    {
      title: '专业',
      dataIndex: 'majorName',
      key: 'majorName',
      width: 110,
    },
    {
      title: '年级',
      dataIndex: 'gradeName',
      key: 'gradeName',
      width: 50,
    },
    {
      title: '班级',
      dataIndex: 'className',
      key: 'className',
      width: 50,
    },
    {
      key: 'id',
      width: 1,
    },
    {
      title: '班主任 ',
      dataIndex: 'classTeacher',
      key: 'classTeacher',
      width: 75,
    },
    {
      title: '学员姓名',
      dataIndex: 'studentName',
      key: 'studentName',
      width: 75,
    },
    {
      title: '学号',
      dataIndex: 'userNo',
      key: 'userNo',
      width: 80,
      textAlign: 'center',
    },
    {
      title: '身份证号码',
      dataIndex: 'idNo',
      key: 'idNo',
      width: 100,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 50,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 110,
    },
    {
      title: '手机号',
      dataIndex: 'mobileNo',
      key: 'mobileNo',
      width: 75,
    },
    {
      title: '项目角色',
      dataIndex: 'position',
      key: 'position',
      width: 75,
    },

    {
      title: '操作',
      key: 'action',

      width: 100,
      render: (row: any) => (
        <>
          <Button
            type="link"
            onClick={() => {
              setCurrentEditObjectUp({
                ...row,
                isModalVisible: true,
              });
            }}
            style={{ padding: '4px 8px' }}
          >
            {' '}
            编辑
          </Button>

          <Button
            type="link"
            onClick={() => {
              showDeleteConfirm({
                ...row,
              });
            }}
            style={{ padding: '4px 8px' }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];
  const [state, setState] = React.useState({
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
  });
  const { loading, selectedRowKeys } = state;
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  function start() {
    setState({ selectedRowKeys: [], loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  }

  function onSelectChange(selectedRowKeys: any) {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    setState({ loading: false, selectedRowKeys });
  }

  const [
    currentEditObjectUp,
    setCurrentEditObjectUp,
  ] = React.useState<UsereditObjectUp>({
    isModalVisible: false,
  });

  const [
    currentEditObjectDown,
    setCurrentEditObjectDown,
  ] = React.useState<UsereditObjectDown>({
    isModalVisible: false,
  });

  const [formObject] = Form.useForm();

  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 10,
    pageSize: 5,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '50', '200', '500'],
    showQuickJumper: true,
  });
  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    const data = await formObject.validateFields();
    console.log(id);

    const ds = {
      ...data,
      id: id,
      current: pageValue,
      size: pageSize,
    };

    const result: any = await request.post(
      '/api/admin/studentInfoManagement/getStudentsSubsidiary',
      qs.stringify(ds),
    );
    console.log('=====================');
    console.log(result);

    if (result.code === 200) {
      const data = result.data.records.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id, //
        userNo: user.userNo, // 	学生ID
        studentName: user.studentName, // 学生
        className: user.className, // 班级
        majorName: user.majorName, //专业
        gradeName: user.gradeName, // 学院名
        idNo: user.idNo, // 	身份证号
        sex: user.sex, // 	年级名
        email: user.email, // 邮箱
        mobileNo: user.mobileNo, // 手机号
        position: user.position, // 	年级ID
        classTeacher: user.classTeacher, // 教师
        collegesName: user.collegesName, // 学院ID
      }));
      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.data.total, //总条数 分页               *******************
      };
      const a = result.data.records[0];
      console.log(a);

      console.log(data);
      setPagination(newPageObject);
      setDataSource(data);
      setLoadingState({ loading: false });
    }
    if (result.code == 201) {
      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.records, //总条数 分页               *******************
      };
      setPagination(newPageObject);
      setDataSource(result.data);
    }
  };

  const searchOnClick = async () => {
    setLoadingState({ loading: true });
    // console.log(1);
    let data = await formObject.validateFields();
    let dataStr = '';
    let ds = {
      ...data,
      stuClass: id,
    };
    for (var n in ds) {
      if (dataStr != '') dataStr += '&';
      dataStr += encodeURIComponent(n) + '=' + encodeURIComponent(ds[n]);
    }
    console.log(dataStr);
    console.log(ds);
    await loadDataSource(ds, 1, pagination.pageSize);
  };

  React.useEffect(() => {
    loadDataSource(null, 1, pagination.pageSize).finally();
  }, []);

  //换页
  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  async function userEditOnClose() {
    await loadDataSource(
      formObject.getFieldsValue(),
      pagination.current,
      pagination.pageSize,
    );
  }

  //重置按钮
  const resetOnClick = () => {
    formObject.resetFields();
  };

  //批量删除
  const deleteLotsOnClick = async (user: any) => {
    console.log(user);
    console.log('///////////////');
    var arr = [].concat(selectedRowKeys);
    var newArr = arr.map((item, index) => {
      // @ts-ignore
      return Number(item.slice(5));
    });
    console.log(newArr);
    const result: any = await request.get(
      '/api/admin/studentInfoManagement/deleteStudents?id=' +
        id +
        '&studentsId=' +
        newArr,
    );
    if (result.code === 200) {
      setTimeout(() => {
        message.success('操作成功！');
      }, 200);
      await loadDataSource(
        formObject.getFieldsValue(),
        pagination.current,
        pagination.pageSize,
      );
    }
  };

  //删除
  const deleteOnClick = async (user: any) => {
    console.log(user.id);
    const data = [user.id];
    console.log(data);
    const ds = {
      studentsId: user.id,
      id: id, //班级id
    };
    console.log(ds);
    const result: any = await request.get(
      '/api/admin/studentInfoManagement/deleteStudents?id=' +
        id +
        '&studentsId=' +
        user.id,
    );
    console.log(result);
    if (result.code == 200) {
      setTimeout(() => {
        message.success('操作成功！');
      }, 200);
      await loadDataSource(
        formObject.getFieldsValue(),
        pagination.current,
        pagination.pageSize,
      );
    }
  };

  function showDeleteConfirm(val: any) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      title: '温馨提示',
      content: '是否删除？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        deleteOnClick(val).then((r) => {
          console.log('ok');
          console.log(val);
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  function showDeleteAllConfirm(val: any) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      title: '温馨提示',
      content: '是否删除所有选中学生？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        if (flag) {
          deleteLotsOnClick(val).then((r) => {
            // console.log('ok')
          });
        } else {
          message.error('请选择需要删除的学生！');
        }
      },
      onCancel() {
        // console.log('Cancel');
      },
    });
  }

  const hasSelected = selectedRowKeys.length > 0;
  const flag = hasSelected;
  return (
    <div>
      <div className="pageMain">
        <div className="pageContent">
          <div className="search" style={{ width: '1300px', height: '140px' }}>
            <div className={styles.searchForm}>
              <Form layout="inline" form={formObject}>
                <Form.Item
                  className="studentInput"
                  label="学员姓名"
                  name="studentName"
                  initialValue=""
                >
                  <Input placeholder="请输入学员姓名..." />
                </Form.Item>
                <Form.Item
                  className="studentInput"
                  label="身份证号"
                  name="idNo"
                >
                  <Input placeholder="请输入身份证号..." />
                </Form.Item>
                <Form.Item
                  className="studentInput"
                  label="学&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号"
                  name="userNo"
                  initialValue=""
                >
                  <Input placeholder="请输入学号..." />
                </Form.Item>
                <Form.Item
                  className="studentInput"
                  label="性别"
                  name="sex"
                  initialValue=""
                >
                  <Select>
                    <Option value="">请选择...</Option>
                    <Option value="男">男</Option>
                    <Option value="女">女</Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  className="studentInput"
                  label="邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱"
                  name="email"
                  initialValue=""
                >
                  <Input placeholder="请输入邮箱..." />
                </Form.Item>
                <Form.Item
                  className="studentInput"
                  label="手机号码"
                  name="mobileNo"
                  initialValue=""
                >
                  <Input placeholder="请输入手机号码..." />
                </Form.Item>

                <Form.Item
                  className="sdSelect"
                  label="项目角色"
                  name="position"
                  initialValue=""
                >
                  <Select>
                    <Option value="">请选择...</Option>
                    <Option value="UI">UI</Option>
                    <Option value="前端">前端</Option>
                    <Option value="后端">后端</Option>
                    <Option value="测试">测试</Option>
                    <Option value="项目经理">项目经理</Option>
                    <Option value="产品经理">产品经理</Option>
                  </Select>
                </Form.Item>

                <Form.Item>
                  <Button type="primary" onClick={searchOnClick}>
                    查询
                  </Button>
                </Form.Item>
                <Button style={{ marginLeft: -20 }} onClick={resetOnClick}>
                  重置
                </Button>
              </Form>
            </div>
          </div>
        </div>
      </div>

      <div style={{ marginBottom: 16 }}>
        <Button
          style={{ margin: '0 10px 10px 0' }}
          type="primary"
          onClick={() => {
            setCurrentEditObjectUp({
              isModalVisible: true,
            });
          }}
        >
          + 新增
        </Button>
        <Button
          style={{ margin: '0 10px 10px 0' }}
          onClick={() => {
            showDeleteAllConfirm({
              selectedRowKeys,
            });
          }}
        >
          批量删除
        </Button>
        <Button
          style={{ margin: '0 10px 10px 0' }}
          type="primary"
          onClick={start}
          disabled={!hasSelected}
          loading={loading}
        >
          重置
        </Button>
        <span style={{ marginLeft: 8 }}>
          {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
        </span>
      </div>
      <Spin tip="Loading..." spinning={loadingState.loading}>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataSource}
          onChange={pageOnChange}
          pagination={pagination}
        />
      </Spin>
      <SdEdit
        editObjectUp={currentEditObjectUp}
        onClose={userEditOnClose}
        editObjectDown={currentEditObjectDown}
      />
    </div>
  );
};
